package cn.edu.cqu.fredyvia.forum.controller;

import cn.edu.cqu.fredyvia.forum.entity.Comment;
import cn.edu.cqu.fredyvia.forum.service.ICommentService;
import cn.edu.cqu.fredyvia.forum.service.ITalkService;
import cn.edu.cqu.fredyvia.forum.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/comment")
public class CommentController extends BaseController {
    @Autowired
    IUserService iUserService;

    @Autowired
    ICommentService iCommentService;

    @Autowired
    ITalkService iTalkService;

    @PostMapping("/add")
    @ResponseBody
//    @Transactional(rollbackFor = {RuntimeException.class})
    public AjaxResult add(@RequestBody Map<String, Object> map) {
        logger.info(map.toString());
//        Talk talk = BeanUtils.toBean(map,Talk.class);
//        System.out.println(map);
        try {
            Comment comment = JSON.parseObject(JSON.toJSONString(map), Comment.class);
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            comment.setUserId(iUserService.getUserByUsername(username).getId());
            comment.setId(null);
//            Talk talk = iTalkService.getById(comment.getTalkId());
//            talk.setTotal_thumb(talk.getTotal_thumb() + 1);
//            return AjaxResult.success(iTalkService.updateById(talk));
            return AjaxResult.success(iCommentService.save(comment));
        } catch (Exception e) {
            return AjaxResult.error("点过赞了");
        }
    }

    //获取某个帖子的全部评论
    @GetMapping("/list")
    @ResponseBody
    public AjaxResult listByTalkId(@RequestParam Integer talkId) {
        return AjaxResult.success(iCommentService.listByTalkId(talkId));
    }
//
//    //获取某一条评论
//    @GetMapping("/oneinfo")
//    @ResponseBody
//    public AjaxResult one(int commentId){
//
//        return AjaxResult.success(iCommentService.one(commentId));
//    }
}
